package com.parking.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.parking.common.core.model.PageInfo;
import com.parking.common.core.model.Result;
import com.parking.common.core.model.StateData;
import com.parking.common.core.util.CardIdUtil;
import com.parking.common.web.util.OssUtil;
import com.parking.dto.RentersUserDto;
import com.parking.dto.UserDto;
import com.parking.dto.UserInfoDto;
import com.parking.dto.UserInfoDtos;
import com.parking.exception.UserException;
import com.parking.exception.UserExceptionCode;
import com.parking.form.*;
import com.parking.user.client.dto.RentersDto;
import com.parking.user.client.inter.UserRenterClient;
import com.parking.user.dao.UserAccountMapper;
import com.parking.user.dao.UserCarMapper;
import com.parking.user.entity.UserAccount;
import com.parking.user.entity.UserCar;
import com.parking.user.entity.UserInfo;
import com.parking.user.dao.UserInfoMapper;
import com.parking.user.service.UserInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Calendar;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 香菜狗带
 * @since 2023年11月28日
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    private UserAccountMapper userAccountMapper;

    @Resource
    private UserCarMapper userCarMapper;
    @Resource
    private OssUtil ossUtil;
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private UserRenterClient userRenterClient;

    /***
     * 查询当前用户信息
     * 参数：
     ("用户Id")：userId;
     */
    @Override
    public UserInfoDto getUserInfoById(Integer userId) {
        UserAccount account = userAccountMapper.selectById(userId);
        if (account==null) {
            throw new UserException(UserExceptionCode.USERINFO_IS_NOT);
        }
        if (account.getUserState()!= StateData.USER_STATE_ENABLE) {
            throw new UserException(UserExceptionCode.USER_ACCOUNT_STATE_ISNOT);
        }
        //用户个人信息
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_account_id",account.getUserId());
        UserInfo userInfo = userInfoMapper.selectOne(wrapper);
        //用户车辆信息
        QueryWrapper<UserCar> carWrapper = new QueryWrapper<>();
        carWrapper.eq("user_info_id",userInfo.getUserInfoId());
        List<UserCar> userCars = userCarMapper.selectList(carWrapper);
        UserInfoDto userDto = BeanUtil.toBean(userInfo, UserInfoDto.class);
        userDto.setUserAccount(account.getUserAccount());
        userDto.setUserAccount(userDto.getUserAccount());
        userDto.setUserCars(userCars);

        return userDto;
    }
    /**
     * 查询全部用户
     * 参数：
     * phone:手机号
     * name:姓名
     * */
    @Override
    public PageInfo getUserInfoAll(SelUserInfoForm form) {
        Page<UserInfo> page = new Page<>(form.getPageNum()!=null?form.getPageNum():1, form.getPageSize()!=null?form.getPageSize():6);
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotEmpty(form.getUserInfoName())) {
            wrapper.like("user_info_name",form.getUserInfoName());
            wrapper.or();
        }
        if (ObjectUtil.isNotEmpty(form.getUserInfoTel())) {
            wrapper.eq("user_info_tel",form.getUserInfoTel());
        }
//        if(ObjectUtil.isNotEmpty(form.getState())&&form.getState()!=1){
//            QueryWrapper<UserAccount> wrapper2 = new QueryWrapper<>();
//            wrapper2.eq("user_state",form.getState());
//            List<UserAccount> userAccounts = userAccountMapper.selectList(wrapper2);
//            System.out.println(userAccounts+"参数");
//            for (UserAccount userAccount : userAccounts) {
//                wrapper.eq("user_account_id",userAccount.getUserId());
//            }
//        }
        userInfoMapper.selectPage(page,wrapper);
        List<UserInfoDtos> userInfoDtos = BeanUtil.copyToList(page.getRecords(), UserInfoDtos.class);
        for (UserInfoDtos dto : userInfoDtos) {
            UserAccount userAccount = userAccountMapper.selectById(dto.getUserAccountId());
            dto.setUserAccount(userAccount.getUserAccount());
            dto.setUserState(userAccount.getUserState());
            QueryWrapper<UserCar> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("user_info_id",dto.getUserInfoId());
            List<UserCar> userCars = userCarMapper.selectList(wrapper1);
            dto.setUserCars(userCars);
        }
        PageInfo pageInfo = BeanUtil.toBean(page, PageInfo.class);
        pageInfo.setRecords(userInfoDtos);
        pageInfo.setPages(page.getPages());
        return pageInfo;
    }
    /**
     * 修改用户信息
     * 参数：
     * phone:手机号
     * userInfoName:姓名
     *
     * */
    @Override
    public void upUserDataById(UpDataForm form, Integer userId) {
        UserAccount account = userAccountMapper.selectById(userId);
        if (account==null) {
            throw new UserException(UserExceptionCode.USERINFO_IS_NOT);
        }
        if (account.getUserState()!= StateData.USER_STATE_ENABLE) {
            throw new UserException(UserExceptionCode.USER_ACCOUNT_STATE_ISNOT);
        }
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_account_id",account.getUserId());
        UserInfo userInfo = userInfoMapper.selectOne(wrapper);
        userInfo.setUserInfoTel(form.getUserInfoTel());
        userInfo.setUserInfoName(form.getUserInfoName());
        userInfoMapper.updateById(userInfo);

    }
    /**
     * 修改头像
     * 参数：
     * image:文件名
     * userInfoImg：用户头像地址
     * fileName:文件名称
     * */
    @Override
    public void upUserInfoImg(UpUserImgForm form) throws IOException {
        UserAccount account = userAccountMapper.selectById(form.getUserId());
        if (account==null) {
            throw new UserException(UserExceptionCode.USERINFO_IS_NOT);
        }
        if (account.getUserState()!= StateData.USER_STATE_ENABLE) {
            throw new UserException(UserExceptionCode.USER_ACCOUNT_STATE_ISNOT);
        }
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_account_id",account.getUserId());
        UserInfo userInfo = userInfoMapper.selectOne(wrapper);
        //上传返回的新地址
        String newPath = ossUtil.uploadFile(form.getImage().getInputStream(), form.getFileName());
        //获取旧的头像地址
        String path = FileNameUtil.getName(userInfo.getUserInfoImg());
        //删除旧地址
        ossUtil.deleteFile(path);
        //修改头像
        userInfo.setUserInfoImg(newPath);
        userInfoMapper.updateById(userInfo);
    }
    /**
     * 实名认证
     * 参数：
     * userInfoName:姓名
     * userInfoCard：用户头像地址
     * userId:用户Id
     * */
    @Override
    public Boolean attestationName(AtteUserNameForm form, Integer userId) throws IOException {
        UserAccount account = userAccountMapper.selectById(userId);
        if (account==null) {
            throw new UserException(UserExceptionCode.USERINFO_IS_NOT);
        }
        if (account.getUserState()!= StateData.USER_STATE_ENABLE) {
            throw new UserException(UserExceptionCode.USER_ACCOUNT_STATE_ISNOT);
        }
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_account_id",userId);
        UserInfo userInfo = userInfoMapper.selectOne(wrapper);
        userInfo.setUserInfoCard(form.getUserInfoCard());
        userInfo.setUserRealName(form.getRealName());
        userInfo.setUserRealNameState(StateData.USER_REALNAME_STATE);
        userInfo.setUserInfoAge(this.getAgeFromIdCard(form.getUserInfoCard()));
        userInfoMapper.updateById(userInfo);
        return CardIdUtil.checkIdCard(form.getUserInfoCard(), form.getRealName());
    }


    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    /**
     * 从身份证获取年龄
     * */
    public  int getAgeFromIdCard(String idCard) {
        int age = 0;
        if (idCard.length() == 18) {
            int birthYear = Integer.parseInt(idCard.substring(6, 10));
            int currentYear = Calendar.getInstance().get(Calendar.YEAR);
            age = currentYear - birthYear;
        }
        return age;
    }
    /**
     * 判断用户信息是否实名
     * 参数: 用户信息Id userInfoId
     * 返回: 用户名称 userInfoName
     * 用户电话 userInfoTel
     * 用户年龄 userInfoAge
     * 用户头像 userInfoImg
     * 方法: 1.判断userInfoId是否存在对应的用户信息 若不存在则抛异常
     * 2.判断对应的用户信息是否实名 若不是则抛异常
     * 3.将用户信息放入Dto返回
     */
    @Override
    public UserInfoDto selectUserInfoById(Integer userInfoId) {
        UserInfo userInfo = userInfoMapper.selectById(userInfoId);
        if (userInfo==null) {
            throw new UserException(UserExceptionCode.USERINFO_IS_NOT);
        }
        if (userInfo.getUserRealNameState()== StateData.USER_REALNAME_STATE_ISNOT) {
            throw new UserException(UserExceptionCode.USER_REAL_NAME_STATE_NO);
        }
        UserInfoDto userInfoDto = BeanUtil.toBean(userInfo, UserInfoDto.class);
        if (userInfoDto==null) {
            throw new UserException(UserExceptionCode.USERINFO_IS_NOT);
        }
        return userInfoDto;
    }
    /**
     * 上传头像
     * 参数：
     * image:文件名
     * */
    @Override
    public void upLoad(String path, Integer userId) {
        UserAccount account = userAccountMapper.selectById(userId);
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_account_id",account.getUserId());
        UserInfo userInfo = userInfoMapper.selectOne(wrapper);
        if (account==null) {
            throw new UserException(UserExceptionCode.USERINFO_IS_NOT);
        }
        if (account.getUserState()!= StateData.USER_STATE_ENABLE) {
            throw new UserException(UserExceptionCode.USER_ACCOUNT_STATE_ISNOT);
        }
        userInfo.setUserInfoImg(path);
        userInfoMapper.updateById(userInfo);
    }
    /**
     * 根据ID查询用户账号
     * 参数: 用户Id userId
     * 返回: 用户Id userId
     *      用户账号 userAccount
     *      用户信息Id userInfoId
     * 方法: 1.判断userId是否存在对应的用户账号 若不存在则抛异常
     *      2.判断对应的用户帐号的状态是否是正常的 若不是则抛异常
     *      3.将用户账号放入Dto返回
     * */
    @Override
    public UserInfo getUserInfo(Integer userId) {
        UserAccount account = userAccountMapper.selectById(userId);
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_account_id",account.getUserId());
        UserInfo userInfo = userInfoMapper.selectOne(wrapper);
        return userInfo;
    }
    /***
     * 出租客
     * 查询根据ID用户信息
     * 参数：
     * ("用户Id")：platformInfoId;
     * ("令牌")：authorization;
     *
     *  返回出租客用户信息dto：
     *  用户信息Id：userInfoId
     *  用户昵称：userInfoName
     *  用户电话：userInfoTel
     */
    @Override
    public RentersUserDto findUserById(Integer rentersId, Integer userInfoId) throws Exception {
        Result<RentersDto> rentersDtoResult = userRenterClient.selectRentersById(rentersId);
        if(rentersDtoResult.getCode()!=200){
            throw new Exception("服务器繁忙");
        }
        RentersDto data = rentersDtoResult.getData();
        if (data==null) {
            throw new UserException(UserExceptionCode.USERINFO_IS_NOT);
        }
        UserInfo userInfo = userInfoMapper.selectById(userInfoId);
        RentersUserDto rentersUserDto = BeanUtil.toBean(userInfo, RentersUserDto.class);
        return rentersUserDto;
    }

    @Override
    public void upUserPass(UpUserPassForm form, Integer userId) {
        UserAccount account = userAccountMapper.selectById(userId);
        if (account==null) {
            throw new UserException(UserExceptionCode.USERINFO_IS_NOT);
        }
        if (account.getUserState()!= StateData.USER_STATE_ENABLE) {
            throw new UserException(UserExceptionCode.USER_ACCOUNT_STATE_ISNOT);
        }
        if (!account.getUserPass().equals(form.getOldPass())) {
            throw new UserException(UserExceptionCode.LOGIN_USER_NOPASS);
        }
        account.setUserPass(form.getNewPass());
        userAccountMapper.updateById(account);
    }
}
